package com.backstage.controller;

import com.alibaba.fastjson.JSON;
import com.backstage.pojo.*;
import com.backstage.service.*;
import com.backstage.utils.JsonResult;
import com.backstage.utils.MD5Utils;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/joinweixinapp")
public class JoinWeixinAppController {

    private static final Logger logger = LoggerFactory.getLogger(JoinWeixinAppController.class);

    @Autowired
    private ContactsUserService contactsUserService;


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult joinweixinapplogin(
            @RequestBody WeixinLoginPost userInfo
            ){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setSuccess(false);

        try {
            WeixinLoginReturnData newWeixinLoginReturnData = new WeixinLoginReturnData();
            ContactsUser userObj = contactsUserService.selectCodeUserWx(userInfo.getCode(), userInfo.getFasongId(), userInfo.getUserInfo());

            newWeixinLoginReturnData.setUserInfo(userObj);
            if(userObj.getId()!=null && userObj.getId() > 0){
                newWeixinLoginReturnData.setToken(MD5Utils.md5("da"+ userObj.getId() + "quanquan.ren"));
            }else{
                newWeixinLoginReturnData.setToken("0");
            }

            jsonResult.setCode("200");
            jsonResult.setData(newWeixinLoginReturnData);
            return jsonResult;

        } catch (Exception e) {
            logger.error("登陆-准备code验证-小程序-" + e.getMessage(), e);
            jsonResult.setCode("systemException");
            jsonResult.setMessage("登陆-准备code验证-小程序-失败！");
            return jsonResult;
        }
    }


    /**
     * 用户 - 关系链详情
     * @param userId 用户ID
     * @param tagName 用户标签名称
     * @return
     */
    @RequestMapping(value = "{userId}/userDetails", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult userDetailsList(@PathVariable("userId") Integer userId, @RequestParam(required = false, defaultValue = "") String tagName){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setSuccess(false);
        try {

            List<WeixinAppUser> userDetailsList = contactsUserService.selectUserDetailsListWxId(userId);
            ContactsUser superiorUser = contactsUserService.selectContactsUserKey(userId);
            if(superiorUser.getContactsid() != null){
                WeixinAppUser superiorUserWeixinApp = contactsUserService.selectContactsUserKeyWx(superiorUser.getContactsid());
                userDetailsList.add(superiorUserWeixinApp);
            }

            for(WeixinAppUser item : userDetailsList){
                Integer id = item.getId();
                List<WeixinAppUser> newContactsUser = contactsUserService.selectUserDetailsListWx(id, tagName);
                item.setContacts_relation_user(newContactsUser);
            }

            Map<String, Object> newData = new HashedMap();
            newData.put("list",userDetailsList);

            if("".equals(tagName)){
                List<ObjectContactsUser> tagList = contactsUserService.selectUserTagList(userId);
                newData.put("tags",tagList);
            }

            WeixinAppUser userObj = contactsUserService.selectUserObjKeyWx(userId);
            newData.put("userObj",userObj);

            jsonResult.setCode("200");
            jsonResult.setData(newData);
            return jsonResult;

        } catch (Exception e) {
            logger.error("获取用户列表错误-小程序-" + e.getMessage(), e);
            jsonResult.setCode("systemException");
            jsonResult.setMessage("获取信息失败！");
            return jsonResult;

        }
    }


    /**
     * 为用户添加 Tab 标签
     * @param userid
     * @param tagname
     * @return
     */
    @RequestMapping(value = "{userid}/setTab", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult setTab(@PathVariable("userid") Integer userid, @RequestParam(required = true) String tagname) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setSuccess(false);

        Integer tagRelationTotal = contactsUserService.selectTagRelationTotal(userid);
        if(tagRelationTotal >= 20){
            jsonResult.setCode("201");
            jsonResult.setMessage("标签不能超过20个");
            return jsonResult;

        }else{
            try {
                List<ObjectContactsUser> tagList = contactsUserService.insertContactsTagWx(userid, tagname);
                jsonResult.setCode("200");
                jsonResult.setData(tagList);
                return jsonResult;

            } catch (Exception e) {
                logger.error("添加标签失败-小程序-" + e.getMessage(), e);
                jsonResult.setCode("systemException");
                jsonResult.setMessage("添加标签失败！");
                return jsonResult;
            }
        }
    }

    /**
     * 删除标签
     * @param userId 用户Id
     * @param tagId 标签ID
     * @return
     */
    @RequestMapping(value = "{userId}/deleteTag", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult deleteTag(@PathVariable("userId") int userId, @RequestParam(required = true) int tagId){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setSuccess(false);
        try {
            List<ObjectContactsUser> tagList = contactsUserService.deleteContactsTagWx(userId, tagId);
            jsonResult.setCode("200");
            jsonResult.setData(tagList);
            return jsonResult;

        } catch (Exception e) {
            logger.error("删除标签失败-小程序-" + e.getMessage(), e);
            jsonResult.setCode("systemException");
            jsonResult.setMessage("删除标签失败！");
            return jsonResult;
        }
    }


}
